<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>layui</title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <link rel="stylesheet" href="../../lib/layui-v2.6.3/css/layui.css" media="all">
  <link rel="stylesheet" href="../../css/public.css" media="all">
  <style>
    body {
      background-color: #ffffff;
    }

    .self-form-item {
      margin-left: 70px;
    }

    .self-input {
      height: auto;
      padding: 5px;
      line-height: 38px;
      border-width: 1px;
      border-style: solid;
      background-color: #fff;
      border-radius: 2px;
      border-color: #eee;
    }

    .self-tag {
      background-color: #ecf5ff;
      display: inline-block;
      height: 32px;
      padding: 0 10px;
      line-height: 30px;
      font-size: 12px;
      user-select: none;
      color: #409eff;
      border: 1px solid #d9ecff;
      border-radius: 4px;
      box-sizing: border-box;
      white-space: nowrap;
      margin-right: 5px;
    }

    .close-icon::before {
      content: "x";
    }

    .self-tag>i::before {
      border-radius: 50%;
      text-align: center;
      position: relative;
      cursor: pointer;
      font-size: 12px;
      height: 16px;
      width: 16px;
      line-height: 16px;
      vertical-align: middle;
      top: -1px;
      right: -5px;
      font-family: element-icons !important;
      speak: none;
      font-style: normal;
      font-weight: 400;
      font-variant: normal;
      text-transform: none;
      line-height: 1;
      vertical-align: baseline;
      display: inline-block;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
    }

    .self-tag>i:hover::before {
      color: #fff;
      background-color: #409eff;
    }
  </style>
</head>

<body>

  <div class="layui-form layuimini-form" lay-filter="pForm">
    <input type="hidden" name="id">
    <div class="layui-form-item">
      <label class="layui-form-label required">试卷标题</label>
      <div class="layui-input-block">
        <input type="text" name="t" lay-verify="required" lay-reqtext="题目标题不能为空" placeholder="请输入题目标题" value=""
          class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label required">考试限时</label>
      <div class="layui-input-block">
        <input type="number" name="m" lay-verify="required" lay-reqtext="限时不能为空" placeholder="请输入考试限时，单位（分钟）" min="1"
          max="360" value="" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label required">选择题目</label>
      <div class="layui-input-block self-input" id="q_ids">
      </div>
    </div>
    <div class="layui-form-item">
      <div class="layui-input-block">
        <button class="layui-btn layui-btn-normal" lay-submit lay-filter="saveBtn">确认保存</button>
      </div>
    </div>
  </div>

  <fieldset class="table-search-fieldset self-form-item">
    <legend>搜索信息</legend>
    <div style="margin: 10px 10px 10px 10px">
      <form class="layui-form layui-form-pane" lay-filter="table-search" action="">
        <div class="layui-form-item">
          <div class="layui-inline">
            <label class="layui-form-label">题目名字</label>
            <div class="layui-input-inline">
              <input type="text" name="question" autocomplete="off" class="layui-input">
            </div>
          </div>
          <div class="layui-inline">
            <label class="layui-form-label">题目类型</label>
            <div class="layui-input-inline">
              <select name="type" autocomplete="off">
                <option value=""></option>
                <option value="radio">单选</option>
                <option value="checkbox">多选</option>
                <option value="judge">是非</option>
              </select>
            </div>
          </div>
          <div class="layui-inline">
            <label class="layui-form-label">创建人</label>
            <div class="layui-input-inline">
              <input type="text" name="name" autocomplete="off" class="layui-input">
            </div>
          </div>
          <div class="layui-inline">
            <button type="submit" id="search" class="layui-btn layui-btn-primary" lay-submit
              lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索</button>
          </div>
        </div>
      </form>
    </div>
  </fieldset>

  <script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
      <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add">添加</button>
    </div>
  </script>

  <script type="text/html" id="currentTableBar">
    <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="add">添加</a>
  </script>

  <div class="self-form-item">
    <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>
  </div>

  <script src="../../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
  <script>
    layui.use(['form'], function () {
      var form = layui.form,
        layer = layui.layer,
        table = layui.table,
        $ = layui.$;

      // #region 修改时要用的方法
      let pid = getQueryVariable('id');
      if (pid) {
        $.get('../../action.php', { a: 'paperg', pid: pid }, function (result, status, xhr) {
          if (result.success) {

            const data = result.data;
            // 填入试卷信息
            form.val('pForm', {
              id: data.id,
              t: data.title,
              m: data.min,
            });

            // 试卷里的题目
            const qs = data.qs;
            if (qs)
              qs.forEach(function (val, index) {
                addTag(val);
              });
            form.render();
          }
        });
      }

      function getQueryVariable(variable) {
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i = 0; i < vars.length; i++) {
          var pair = vars[i].split("=");
          if (pair[0] == variable) { return pair[1]; }
        }
        return (false);
      }

      // #endregion

      $("#q_ids").on('click', 'i', (event, args) => {
        let id = $(event.target).parent().text()
        let obj = $(event.target).parent()
        obj.remove()
        let index = checkIds.indexOf(id)
        if (index >= 0)
          checkIds.splice(index, 1)
      })

      table.render({
        elem: '#currentTableId',
        url: '../../action.php?a=quesg',
        toolbar: '#toolbarDemo',
        cols: [
          [{
            type: "checkbox",
            width: 50
          }, {
            field: 'id',
            width: 80,
            title: 'id',
            sort: true
          }, {
            field: 'n',
            width: 100,
            title: '创建人',
            sort: true
          }, {
            field: 'q',
            width: 800,
            title: '题目'
          }, {
            field: 'an',
            width: 80,
            title: '答案',
            sort: true
          }, {
            field: 't',
            width: 80,
            title: '类型',
            sort: true
          }, {
            field: 'cd',
            width: 180,
            title: '创建时间',
            sort: true
          }, {
            title: '操作',
            minWidth: 100,
            toolbar: '#currentTableBar',
            align: "center"
          }]
        ],
        limits: [10, 15, 20, 25, 50, 100],
        limit: 10,
        page: true,
        skin: 'line',
        even: true,
        done: function (res, curr, count) {
          //如果是异步请求数据方式，res即为你接口返回的信息。
          // 当前页码
          // 数据总量
          //如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
          if (res && res.success !== undefined && !res.success) {
            let lindex = layer.alert(res.message);
            setTimeout(() => {
              layer.close(lindex);
            }, 2000);

          } else if (res.code !== 0) {
            let lindex = layer.alert(res.msg);
            setTimeout(() => {
              layer.close(lindex);
            }, 2000);
          }
        },
        error: function (errObj, result) {
          console.log(errObj, result);
        }
      });

      // 监听搜索操作
      form.on('submit(data-search-btn)', function (data) {
        var result = JSON.stringify(data.field);
        // layer.alert(result, {
        //     title: '最终的搜索信息'
        // });

        //执行搜索重载
        table.reload('currentTableId', {
          page: {
            curr: 1
          },
          where: {
            searchParams: result
          }
        }, 'data');

        return false;
      });

      /**
       * toolbar监听事件
       */
      table.on('toolbar(currentTableFilter)', function (obj) {
        let checkStatus = table.checkStatus('currentTableId')
        if (obj.event === 'add') { // 监听添加操作
          checkStatus.data.forEach(item => {
            let id = item.id
            addTag(id)
          })
        }

      });


      // 监听表格复选框选择
      table.on('checkbox(currentTableFilter)', function (obj) {
        let checkStatus = table.checkStatus('currentTableId')
      });

      // 工具栏事件
      table.on('tool(currentTableFilter)', function (obj) {
        let data = obj.data
        if (obj.event === 'add') {
          addTag(data.id)
        }
      });

      /**
       * 保存的题目id
       */
      let checkIds = []

      /**
       * @description: 添加标签
       * @param {*} s_id
       * @return {*}
       */
      function addTag(s_id) {
        let t = checkIds.find(id => id === s_id)
        if (!t) {
          // 样式模板
          let tem_tag = `<span class="self-tag">${s_id}<i class="close-icon"></i></span>`
          // 附加到标签容器里
          $('#q_ids').append(tem_tag)
          // 保存题目id后续提交
          checkIds.push(s_id)
        }
      }

      /**
       * @description: 获取保存的题目id
       * @param {*}
       * @return {*}
       */
      function getIds() {
        // 没有选中题目返回空
        if (checkIds.length < 1) return undefined;

        // 缓存 请求query
        let s_ids = 'ids=';
        checkIds.forEach(item => {
          s_ids += item + ',';
        })
        return s_ids;
      }


      // 监听搜索操作
      form.on('submit(data-search-btn)', function (data) {
        var result = JSON.stringify(data.field);
        layer.alert(result, {
          title: '最终的搜索信息'
        });

        //执行搜索重载
        table.reload('currentTableId', {
          page: {
            curr: 1
          }
          , where: {
            searchParams: result
          }
        }, 'data');

        return false;
      });

      // 监听保存提交
      form.on('submit(saveBtn)', function (data) {


        // 题目等提交数据
        let formData = ''
        Object.keys(data.field).forEach((key) => {
          formData += key + "=" + data.field[key] + "&";
        })

        // 题目
        let ids = getIds()
        if (ids) {
          formData += ids + "&"
        }
        else {
          layer.msg("请选择题目！")
          return false;
        }

        // layer.alert(formData)

        // return false

        $.ajax({
          url: '../../action.php?a=papera',
          method: 'POST',
          data: formData,
          contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
          success: function (result, status) {
            let json = result
            if (json.success) {
              layer.msg(json.message, {
                time: 0
              });

              setTimeout(() => {
                let iframeIndex = parent.layer.getFrameIndex(window.name);
                parent.layer.close(iframeIndex);
              }, 2000);
            } else {
              layer.alert(json.message)
            }
          }
        })

        return false;
      });

    });
  </script>
</body>

</html>